package com.rr.middle;

import java.util.Arrays;
import java.util.List;

/**
 * @author zhuangcanrun
 * @Date 2022/01/18/12:42
 * @description
 **/
/*
 * https://leetcode-cn.com/problems/minimum-time-difference/
 * */
public class FindMinDifference {
    public int findMinDifferenceBad(List<String> timePoints) {
        int ans = Integer.MAX_VALUE;
        int size = timePoints.size();
        int[] nums = new int[size];
        for (int i = 0; i < size; i++) {
            String s = timePoints.get(i);
            String[] split = s.split(":");
            nums[i] = Integer.parseInt(split[0]) * 60 + Integer.parseInt(split[1]);
        }
        Arrays.sort(nums);
        for (int i = 1; i < size; i++) {
            int temp = nums[i] - nums[i - 1];
            ans = getMinNum(nums[i], nums[i - 1], ans);
            temp = temp > 12 * 60 ? Math.abs(temp - 24 * 60) : temp;
            ans = Math.min(temp, ans);
        }
        return getMinNum(nums[size - 1], nums[0], ans);
    }

    private Integer getMinNum(int a, int b,int ans) {
        int temp = a - b;
        temp = temp > 12 * 60 ? Math.abs(temp - 24 * 60) : temp;
        return Math.min(temp, ans);
    }

    /*
    * 桶排序
    * */
    public int findMinDifferenceGood(List<String> timePoints) {
        int n = timePoints.size();
        if (n >= 1440) return 0;
        int[] cnts = new int[1440 * 2 + 10];
        for (String s : timePoints) {
            String[] ss = s.split(":");
            int h = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
            cnts[h * 60 + m]++;
            cnts[h * 60 + m + 1440]++;
        }
        int ans = 1440, last = -1;
        for (int i = 0; i <= 1440 * 2 && ans != 0; i++) {
            if (cnts[i] == 0) continue;
            if (cnts[i] > 1) ans = 0;
            else if (last != -1) {
                ans = Math.min(ans, i - last);
            }
            last = i;
        }
        return ans;
    }

    public static void main(String[] args) {
        FindMinDifference findMinDifference = new FindMinDifference();
        System.out.println(findMinDifference.findMinDifferenceGood(Arrays.asList("00:00","04:00","22:00")));
    }
}
